package cn.sitedev.prototype.deep;

import lombok.Data;

import java.io.*;
import java.util.List;

/**
 * @author qchen
 * @description 深克隆
 * @date 2020/9/18 1:30
 */
@Data
public class ConcretePrototype implements Cloneable, Serializable {

    private int age;
    private String name;
    private List<String> hobbies;

    /**
     * 浅克隆
     *
     * @return
     */
    @Override
    public ConcretePrototype clone() {
        try {
            return (ConcretePrototype) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 深克隆
     *
     * @return
     */
    public ConcretePrototype deepClone() {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // 序列化 java对象=>字节数组
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            // 字节数=> java独对象
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            return (ConcretePrototype) ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
